package com.jinzheng.qhnetty.util;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;


/**
 * @author: KD
 * @create：2022/11/19
 * @description: 回显客户端 —— 发送消息并接收服务器回显
 */
@Slf4j
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = ((ByteBuf) msg);
                                log.debug("服务器响应信息：{}", buf.toString(Charset.defaultCharset()));
                                buf.release();   //释放ByteBuf
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 15236))
                .sync()
                .channel()
                .writeAndFlush(ByteBufAllocator.DEFAULT.buffer().writeBytes("world".getBytes()));
    }
}
